﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FCT551.Helper
{
    public class TrackableCollection<T> : ObservableCollection<T> where T : System.ComponentModel.INotifyPropertyChanged
    {
        public event EventHandler<ItemPropertyChangedEventArgs<T>> ItemPropertyChanged;

        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            base.OnCollectionChanged(e);

            // 订阅新增元素的属性变更
            if (e.NewItems != null)
            {
                foreach (T item in e.NewItems)
                {
                    item.PropertyChanged += OnItemPropertyChanged;
                }
            }

            // 取消已移除元素的订阅
            if (e.OldItems != null)
            {
                foreach (T item in e.OldItems)
                {
                    item.PropertyChanged -= OnItemPropertyChanged;
                }
            }
        }

        private void OnItemPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            ItemPropertyChanged?.Invoke(this, new ItemPropertyChangedEventArgs<T>((T)sender, e.PropertyName));
        }
    }

    public class ItemPropertyChangedEventArgs<T> : EventArgs
    {
        public T Item { get; }
        public string PropertyName { get; }

        public ItemPropertyChangedEventArgs(T item, string propertyName)
        {
            Item = item;
            PropertyName = propertyName;
        }
    }
}